package net.wicp.tams.commons.binlog.bean;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang.ArrayUtils;

import lombok.Builder;
import lombok.Data;
import net.wicp.tams.commons.io.InputStreamAssit;

@Data
@Builder
public class PacketBean {
	private int sequence;
	private byte[] body;

	// 扩展
	private byte packetMarker;
	private EventBean eventBean;

	public int getLength() {
		return body.length;
	}

	public static PacketBean buildBean(InputStream in) throws IOException {
		InputStreamAssit isAssit = new InputStreamAssit(in);
		int length = isAssit.readInt(3);
		int sequence = isAssit.readInt(1);
		byte[] body = isAssit.readBytes(length);
		byte packetMarker = body[0];
		return PacketBean.builder().sequence(sequence).body(body).packetMarker(packetMarker).build();
	}

	public static PacketBean buildEventBean(InputStream in,String fileName) throws IOException {
		InputStreamAssit isAssit = new InputStreamAssit(in);
		int length = isAssit.readInt(3);
		int sequence = isAssit.readInt(1);
		byte[] body = isAssit.readBytes(length);
		byte packetMarker = body[0];
		EventBean eventBean = new EventBean(ArrayUtils.subarray(body, 1, body.length));
		eventBean.setFileName(fileName);
		return PacketBean.builder().sequence(sequence).body(body).packetMarker(packetMarker).eventBean(eventBean)
				.build();
	}

}
